import {Component, OnInit} from '@angular/core';
import {UntypedFormBuilder, UntypedFormGroup, Validators} from '@angular/forms';
import {CommonParams} from '../../../utils/common-params';
import {Response} from '../../../utils/response';
import {ConstantsService} from '../../../utils/constants.service';
import {Router} from '@angular/router';
import {MyStorageService} from '../../../utils/my.storage.service';
import {ApiService} from '../../../utils/api.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  validateForm: UntypedFormGroup;
  loging = false;
  projectName;
  loadingIndex;
  nowYear = new Date().getFullYear();

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(i)) {
        const control = this.validateForm.controls[i];
        control.markAsDirty();
        control.updateValueAndValidity();
      }
    }
    if (this.validateForm.valid) {
      this.loging = true;
      this.api.login(this.validateForm.value).subscribe((res: Response) => {
        this.constants.auto(res);
        this.loging = false;
        this.constants.removeMsg(this.loadingIndex);
        if (res.isSuccess) {
          this.storage.set(CommonParams.tokenName, res.data[CommonParams.tokenName]);
          this.storage.set(CommonParams.userIdName, res.data[CommonParams.userIdName]);
          this.storage.set(CommonParams.userName, res.data[CommonParams.userName]);

          if (this.validateForm.value.remember) {
            this.storage.setObject(CommonParams.loginUserName, this.validateForm.value);
          } else {
            this.storage.delete(CommonParams.loginUserName);
          }
          this.router.navigate(['draw-lots']).then(() => {
          });
        } else {
          this.validateForm.patchValue({password: ''});
        }
      }, error => {
        this.constants.removeMsg(this.loadingIndex);
        this.loging = false;
        this.validateForm.patchValue({password: ''});
      });
    }
  }

  constructor(private fb: UntypedFormBuilder, private router: Router, private api: ApiService,
              private constants: ConstantsService, private storage: MyStorageService) {
  }

  ngOnInit(): void {
    this.projectName = this.constants.getProjectTitle();
    this.validateForm = this.fb.group({
      userName: ['', [Validators.required]],
      password: ['', [Validators.required]],
      remember: [false]
    });
    const loginUser = this.storage.getObject(CommonParams.loginUserName);
    this.validateForm.patchValue(Object.assign(loginUser, {remember: loginUser.remember === true}));
    if (loginUser.userName && loginUser.password) {
      this.loging = true;
      this.loadingIndex = this.constants.loading('自动登录中...');
      setTimeout(() => {
        this.submitForm();
      }, 1500);
    }
  }
}
